package sin.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 工具类，处理request,response
 * @author francis
 *
 */
public class ServletUtils {
	
	/**
	 * 获取URL链接中共通的部分
	 * @param request
	 * @return
	 */
	public static String getHttpRoot(HttpServletRequest request) {
		return "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
	}
	
	public static void output(HttpServletResponse response ,String content) {
		try {
			PrintWriter out = response.getWriter();
			out.print(content);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Map<String,Object> getParams(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		for(Object key : request.getParameterMap().keySet()) {
			map.put((String)key, request.getParameter((String)key));
		}
		return map;
	}
	
	public static Map<String,Object> getAttrs(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Enumeration<?> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			Object value = request.getParameter(key);
			request.setAttribute(key, value);
			map.put(key, value);
		}
		return map;
	}
	
	public static void putParamToAttr(HttpServletRequest request,String name) {
		request.setAttribute(name, request.getParameter(name));
	}
	
	public static void putParamToAttr(HttpServletRequest request,String... names) {
		for(String name : names) request.setAttribute(name, request.getParameter(name));
	}
}
